﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Sharp.DataTransferObject;
using Sharp.Infrastructure.Interfaces;

namespace Sharp.Portal.Mvc
{
    public class PermissionScan
    {

        /// <summary>
        /// 获取程序集的功能点
        /// </summary>
        /// <returns></returns>
        public IList<PermissionDTO> GetAllActionByAssembly(List<PermissionDTO> result, Assembly assembly)
        {
            if (result == null)
                result = new List<PermissionDTO>();

            var types = assembly.GetTypes();

            foreach (var type in types.Where(x => x.IsSubclassOf(typeof(Controller))))
            {
                var members = type.GetMethods();
                foreach (var member in members)
                {
                    var permissionAttribute = member.GetCustomAttributes<PermissionAttribute>(true).FirstOrDefault();
                    if (permissionAttribute == null)
                    {
                        continue;
                    }
                    var areas = "";
                    if (type.Namespace.Contains(".Areas."))
                    {
                        areas += Regex.Match(type.Namespace, @"Areas\.(.*?)\.Controllers").Groups[1].Value;
                    }


                    var ap = new PermissionDTO
                    {
                        Title = permissionAttribute.Name,
                        OrderIndex = permissionAttribute.Order,
                        Code = permissionAttribute.Code,
                        Route = "/" + member.DeclaringType.Name.Substring(0, member.DeclaringType.Name.Length - 10) +
                            "/" + member.Name,// 去掉“Controller”后缀
                        Category = permissionAttribute.Category,
                        SystemCode = areas
                    };

                    if (ap.Id.IsEmpty())
                        ap.Id = Guid.Parse($"{ap.Code}_{ap.SystemCode}_{ap.Category}".Md5());


                    var parent = result.FirstOrDefault(c =>
                        !ap.IsShortcut && c.SystemCode == ap.SystemCode &&
                        ap.Code.StartsWith(c.Code) &&
                        c.Code.Length == ap.Code.Length - 3);
                    if (parent != null)
                    {
                        ap.ParentId = parent.Id;
                    }
                    else
                    {
                        ap.ParentId = null;
                    }

                    //不被配置进入菜单，功能项就成为孤立的了。
                    if (ap.ParentId == null && ap.Category == PermissionCategory.OperationItem)
                    {
                        continue;
                    }

                    if (!permissionAttribute.Parent.IsNullOrEmpty())
                    {
                        ap.Route = permissionAttribute.Parent + "/" + member.Name;
                    }

                    if (ap.Code.IsNotNullOrEmpty())
                        result.Add(ap);
                }


            }
            return result.Distinct(new PermissionComparer()).ToList();
        }
    }

    public class PermissionComparer : IEqualityComparer<PermissionDTO>
    {
        #region IEqualityComparer<User> 成员  
        public bool Equals(PermissionDTO x, PermissionDTO y)
        {
            if (x.Code == y.Code && x.SystemCode == y.SystemCode && x.Category == y.Category)
                return true;
            else
                return false;
        }

        public int GetHashCode(PermissionDTO obj)
        {
            return 0;
        }
        #endregion
    }
}
